package org.jeecg.modules.mes.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.modules.mes.entity.MesProductionPlan;
import org.jeecg.modules.mes.entity.MesProductionPlanTask;
import org.jeecg.modules.mes.service.IMesProductionPlanService;
import org.jeecg.modules.mes.service.IMesProductionPlanTaskService;
import org.jeecg.modules.oms.entity.ProductSalesOrder;
import org.jeecg.modules.oms.service.IProductSalesOrderService;
import org.jeecg.modules.mes.vo.MesCreatePlanFromTemplateVO;
import org.jeecg.modules.mes.vo.MesCustomPlanCreateVO;
import org.jeecg.modules.mes.vo.MesProductionPlanVO;
import org.jeecg.modules.mes.vo.MesMergedPlanCreateVO;
import org.jeecg.modules.mes.vo.MesProductionPlanDetailVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * @Description: 生产计划管理
 * @Author: jeecg-boot
 * @Date: 2025-01-21
 * @Version: V1.0
 */
@Api(tags = "生产计划管理")
@RestController
@RequestMapping("/mes/plan")
@Slf4j
public class MesProductionPlanController extends JeecgController<MesProductionPlan, IMesProductionPlanService> {

    @Autowired
    private IMesProductionPlanService mesProductionPlanService;
    
    @Autowired
    private IProductSalesOrderService productSalesOrderService;
    
    @Autowired
    private IMesProductionPlanTaskService mesProductionPlanTaskService;

    /**
     * 分页列表查询
     *
     * @param mesProductionPlan
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "生产计划-分页列表查询")
    @ApiOperation(value = "生产计划-分页列表查询", notes = "生产计划-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<MesProductionPlan>> queryPageList(MesProductionPlan mesProductionPlan,
                                                          @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                          @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                          HttpServletRequest req) {
        QueryWrapper<MesProductionPlan> queryWrapper = QueryGenerator.initQueryWrapper(mesProductionPlan, req.getParameterMap());
        queryWrapper.orderByDesc("priority");
        queryWrapper.orderByAsc("status");
        Page<MesProductionPlan> page = new Page<MesProductionPlan>(pageNo, pageSize);
        IPage<MesProductionPlan> pageList = mesProductionPlanService.page(page, queryWrapper);
        
        // 填充orderNo字段和任务统计
        if (pageList.getRecords() != null && !pageList.getRecords().isEmpty()) {
            for (MesProductionPlan plan : pageList.getRecords()) {
                // 填充订单编号
                if (plan.getOrderId() != null && !plan.getOrderId().isEmpty() && 
                    (plan.getOrderNo() == null || plan.getOrderNo().isEmpty())) {
                    try {
                        ProductSalesOrder order = productSalesOrderService.getById(plan.getOrderId());
                        if (order != null && order.getOrderNo() != null) {
                            plan.setOrderNo(order.getOrderNo());
                        }
                    } catch (Exception e) {
                        log.warn("获取订单编号失败，orderId: {}", plan.getOrderId(), e);
                    }
                }
                
                // 统计任务数据
                try {
                    List<MesProductionPlanTask> tasks = mesProductionPlanTaskService.getTasksByPlanId(plan.getId());
                    int totalTasks = tasks.size();
                    int completedTasks = 0;
                    int pendingTasks = 0;
                    
                    for (MesProductionPlanTask task : tasks) {
                        if (task.getStatus() != null) {
                            if (task.getStatus() == 3) { // 已完成
                                completedTasks++;
                            } else if (task.getStatus() == 0) { // 待领取
                                pendingTasks++;
                            }
                            // 状态1-已领取, 2-进行中, 4-暂停 不计入待处理，这些是正在处理的任务
                        }
                    }
                    
                    // 设置任务统计数据到计划对象
                    plan.setTotalTasks(totalTasks);
                    plan.setCompletedTasks(completedTasks);
                    plan.setPendingTasks(pendingTasks);
                    
                } catch (Exception e) {
                    log.warn("统计计划任务数据失败，planId: {}", plan.getId(), e);
                    // 设置默认值
                    plan.setTotalTasks(0);
                    plan.setCompletedTasks(0);
                    plan.setPendingTasks(0);
                }
            }
        }
        
        return Result.OK(pageList);
    }

    /**
     * 添加
     *
     * @param mesProductionPlan
     * @return
     */
    @AutoLog(value = "生产计划-添加")
    @ApiOperation(value = "生产计划-添加", notes = "生产计划-添加")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody MesProductionPlan mesProductionPlan) {
        mesProductionPlanService.save(mesProductionPlan);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param mesProductionPlan
     * @return
     */
    @AutoLog(value = "生产计划-编辑")
    @ApiOperation(value = "生产计划-编辑", notes = "生产计划-编辑")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody MesProductionPlan mesProductionPlan) {
        mesProductionPlanService.updateById(mesProductionPlan);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "生产计划-通过id删除")
    @ApiOperation(value = "生产计划-通过id删除", notes = "生产计划-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        //恢复订单状态为6
        productSalesOrderService.update(new UpdateWrapper<ProductSalesOrder>()
                .eq("id", mesProductionPlanService.getById(id).getOrderId()).set("status", 6));
        mesProductionPlanService.removeById(id);
        mesProductionPlanTaskService.remove(new QueryWrapper<MesProductionPlanTask>().eq("plan_id", id));
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "生产计划-批量删除")
    @ApiOperation(value = "生产计划-批量删除", notes = "生产计划-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.mesProductionPlanService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    @AutoLog(value = "生产计划-通过id查询")
    @ApiOperation(value = "生产计划-通过id查询", notes = "生产计划-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<MesProductionPlan> queryById(@RequestParam(name = "id", required = true) String id) {
        MesProductionPlan mesProductionPlan = mesProductionPlanService.getById(id);
        if (mesProductionPlan == null) {
            return Result.error("未找到对应数据");
        }
        if (mesProductionPlan.getOrderId() != null && !mesProductionPlan.getOrderId().isEmpty() &&
                (mesProductionPlan.getOrderNo() == null || mesProductionPlan.getOrderNo().isEmpty())) {
            // 通过orderId查询orderNo
            try {
                ProductSalesOrder order = productSalesOrderService.getById(mesProductionPlan.getOrderId());
                if (order != null && order.getOrderNo() != null) {
                    mesProductionPlan.setOrderNo(order.getOrderNo());
                }
            } catch (Exception e) {
                log.warn("获取订单编号失败，orderId: {}", mesProductionPlan.getOrderId(), e);
            }
        }
        return Result.OK(mesProductionPlan);
    }

    /**
     * 基于模板创建生产计划
     * 支持按产品明细生成具体任务的新逻辑
     *
     * @param createVO
     * @return
     */
    @AutoLog(value = "生产计划-基于模板创建")
    @ApiOperation(value = "生产计划-基于模板创建", notes = "基于模板创建生产计划，支持按产品明细生成具体任务")
    @PostMapping(value = "/create-from-template")
    public Result<String> createFromTemplate(@RequestBody MesCreatePlanFromTemplateVO createVO) {
        try {
            // 参数验证
            if (createVO == null) {
                return Result.error("请求参数不能为空");
            }
            if (createVO.getTemplateId() == null || createVO.getTemplateId().trim().isEmpty()) {
                return Result.error("请选择生产模板");
            }
            
            log.info("开始基于模板创建生产计划，模板ID: {}", createVO.getTemplateId());
            
            String planId = mesProductionPlanService.createPlanFromTemplate(createVO);
            
            log.info("基于模板创建生产计划成功，计划ID: {}", planId);
            
            return Result.OK( "基于模板创建生产计划成功！");
        } catch (Exception e) {
            log.error("基于模板创建生产计划失败，模板ID: {}, 错误信息: {}", 
                    createVO != null ? createVO.getTemplateId() : "null", e.getMessage(), e);
            return Result.error("创建失败：" + e.getMessage());
        }
    }

    /**
     * 自定义创建生产计划
     * 支持按产品明细生成具体任务的新逻辑
     *
     * @param createVO
     * @return
     */
    @AutoLog(value = "生产计划-自定义创建")
    @ApiOperation(value = "生产计划-自定义创建", notes = "自定义创建生产计划，支持按产品明细生成具体任务")
    @PostMapping(value = "/create-custom")
    public Result<String> createCustomPlan(@RequestBody MesCustomPlanCreateVO createVO) {
        try {
            // 参数验证
            if (createVO == null) {
                return Result.error("请求参数不能为空");
            }
            if (createVO.getPlanName() == null || createVO.getPlanName().trim().isEmpty()) {
                return Result.error("请输入计划名称");
            }
            if (createVO.getTasks() == null || createVO.getTasks().isEmpty()) {
                return Result.error("请配置工种任务");
            }
            
            // 计算预期生成的任务数量
            int expectedTaskCount = createVO.getTasks().size();
            if (createVO.getOrderDetailIds() != null && !createVO.getOrderDetailIds().isEmpty()) {
                expectedTaskCount = createVO.getOrderDetailIds().size() * createVO.getTasks().size();
            }
            
            log.info("开始自定义创建生产计划，计划名称: {}, 工种数量: {}, 产品明细数量: {}", 
                    createVO.getPlanName(), createVO.getTasks().size(), 
                    createVO.getOrderDetailIds() != null ? createVO.getOrderDetailIds().size() : 0);
            
            String planId = mesProductionPlanService.createCustomPlan(createVO);
            
            log.info("自定义创建生产计划成功，计划ID: {}, 预期生成任务数量: {}", planId, expectedTaskCount);
            
            return Result.OK(String.format("自定义创建生产计划成功，已生成 %d 个具体任务", expectedTaskCount));
        } catch (Exception e) {
            log.error("自定义创建生产计划失败，计划名称: {}, 错误信息: {}", 
                    createVO != null ? createVO.getPlanName() : "null", e.getMessage(), e);
            return Result.error("创建失败：" + e.getMessage());
        }
    }

    /**
     * 获取可领取的任务
     *
     * @param employeeId
     * @param workTypeId
     * @return
     */
    @AutoLog(value = "生产计划-获取可领取任务")
    @ApiOperation(value = "生产计划-获取可领取任务", notes = "生产计划-获取可领取任务")
    @GetMapping(value = "/available-tasks")
    public Result<List<MesProductionPlanTask>> getAvailableTasks(@RequestParam String employeeId,
                                                                 @RequestParam(required = false) String workTypeId) {
        List<MesProductionPlanTask> tasks = mesProductionPlanService.getAvailableTasks(employeeId, workTypeId);
        return Result.OK(tasks);
    }

    /**
     * 领取任务
     *
     * @param taskId
     * @param employeeId
     * @return
     */
    @AutoLog(value = "生产计划-领取任务")
    @ApiOperation(value = "生产计划-领取任务", notes = "生产计划-领取任务")
    @PostMapping(value = "/claim-task")
    public Result<String> claimTask(@RequestParam String taskId, @RequestParam String employeeId) {
        try {
            mesProductionPlanService.claimTask(taskId, employeeId);
            return Result.OK("任务领取成功！");
        } catch (Exception e) {
            log.error("任务领取失败", e);
            return Result.error("领取失败：" + e.getMessage());
        }
    }

    /**
     * 获取我的任务
     *
     * @param employeeId
     * @return
     */
    @AutoLog(value = "生产计划-获取我的任务")
    @ApiOperation(value = "生产计划-获取我的任务", notes = "生产计划-获取我的任务")
    @GetMapping(value = "/my-tasks")
    public Result<List<MesProductionPlanTask>> getMyTasks(@RequestParam String employeeId) {
        List<MesProductionPlanTask> tasks = mesProductionPlanService.getMyTasks(employeeId);
        return Result.OK(tasks);
    }

    /**
     * 获取可领取的生产计划
     *
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    @AutoLog(value = "生产计划-获取可领取计划")
    @ApiOperation(value = "生产计划-获取可领取计划", notes = "获取状态为已下发且未被领取的生产计划")
    @GetMapping(value = "/available")
    public Result<IPage<MesProductionPlan>> getAvailablePlans(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                                              HttpServletRequest req) {
        QueryWrapper<MesProductionPlan> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("status", 2); // 已下发状态

        Page<MesProductionPlan> page = new Page<MesProductionPlan>(pageNo, pageSize);
        IPage<MesProductionPlan> pageList = mesProductionPlanService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 获取我的生产计划
     *
     * @param employeeId
     * @param pageNo
     * @param pageSize
     * @return
     */
    @AutoLog(value = "生产计划-获取我的计划")
    @ApiOperation(value = "生产计划-获取我的计划", notes = "获取当前用户领取的生产计划")
    @GetMapping(value = "/my")
    public Result<IPage<MesProductionPlan>> getMyPlans(@RequestParam String employeeId,
                                                       @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                       @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        QueryWrapper<MesProductionPlan> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("claimed_by", employeeId);
        queryWrapper.in("status", 3, 4); // 进行中或已暂停状态
        queryWrapper.orderByDesc("priority");

        Page<MesProductionPlan> page = new Page<MesProductionPlan>(pageNo, pageSize);
        IPage<MesProductionPlan> pageList = mesProductionPlanService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 获取历史生产计划
     *
     * @param employeeId
     * @param pageNo
     * @param pageSize
     * @return
     */
    @AutoLog(value = "生产计划-获取历史计划")
    @ApiOperation(value = "生产计划-获取历史计划", notes = "获取当前用户已完成的生产计划")
    @GetMapping(value = "/history")
    public Result<IPage<MesProductionPlan>> getHistoryPlans(@RequestParam String employeeId,
                                                            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        QueryWrapper<MesProductionPlan> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("claimed_by", employeeId);
        queryWrapper.eq("status", 5); // 已完成状态
        queryWrapper.orderByDesc("update_time");
        
        Page<MesProductionPlan> page = new Page<MesProductionPlan>(pageNo, pageSize);
        IPage<MesProductionPlan> pageList = mesProductionPlanService.page(page, queryWrapper);
        return Result.OK(pageList);
    }

    /**
     * 领取生产计划
     *
     * @param planId
     * @param employeeId
     * @param remark
     * @return
     */
    @AutoLog(value = "生产计划-领取计划")
    @ApiOperation(value = "生产计划-领取计划", notes = "员工领取生产计划")
    @PostMapping(value = "/claim")
    public Result<String> claimPlan(@RequestParam String planId, 
                                    @RequestParam String employeeId,
                                    @RequestParam(required = false) String remark) {
        try {
            mesProductionPlanService.claimPlan(planId, employeeId, remark);
            return Result.OK("生产计划领取成功！");
        } catch (Exception e) {
            log.error("生产计划领取失败", e);
            return Result.error("领取失败：" + e.getMessage());
        }
    }

    /**
     * 开始生产计划
     *
     * @param planId
     * @param employeeId
     * @return
     */
    @AutoLog(value = "生产计划-开始计划")
    @ApiOperation(value = "生产计划-开始计划", notes = "开始执行生产计划")
    @PostMapping(value = "/start")
    public Result<String> startPlan(@RequestParam String planId, 
                                    @RequestParam String employeeId) {
        try {
            mesProductionPlanService.startPlan(planId, employeeId);
            return Result.OK("生产计划已开始！");
        } catch (Exception e) {
            log.error("生产计划开始失败", e);
            return Result.error("开始失败：" + e.getMessage());
        }
    }

    /**
     * 暂停生产计划
     *
     * @param planId
     * @param employeeId
     * @return
     */
    @AutoLog(value = "生产计划-暂停计划")
    @ApiOperation(value = "生产计划-暂停计划", notes = "暂停执行生产计划")
    @PostMapping(value = "/pause")
    public Result<String> pausePlan(@RequestParam String planId, 
                                    @RequestParam String employeeId) {
        try {
            mesProductionPlanService.pausePlan(planId, employeeId);
            return Result.OK("生产计划已暂停！");
        } catch (Exception e) {
            log.error("生产计划暂停失败", e);
            return Result.error("暂停失败：" + e.getMessage());
        }
    }

    /**
     * 恢复生产计划
     *
     * @param planId
     * @param employeeId
     * @return
     */
    @AutoLog(value = "生产计划-恢复计划")
    @ApiOperation(value = "生产计划-恢复计划", notes = "恢复执行生产计划")
    @PostMapping(value = "/resume")
    public Result<String> resumePlan(@RequestParam String planId, 
                                     @RequestParam String employeeId) {
        try {
            mesProductionPlanService.resumePlan(planId, employeeId);
            return Result.OK("生产计划已恢复！");
        } catch (Exception e) {
            log.error("生产计划恢复失败", e);
            return Result.error("恢复失败：" + e.getMessage());
        }
    }

    /**
     * 完成生产计划
     *
     * @param planId
     * @param employeeId
     * @param completedQuantity
     * @param actualHours
     * @param remark
     * @return
     */
    @AutoLog(value = "生产计划-完成计划")
    @ApiOperation(value = "生产计划-完成计划", notes = "完成生产计划")
    @PostMapping(value = "/complete")
    public Result<String> completePlan(@RequestParam String planId, 
                                       @RequestParam String employeeId,
                                       @RequestParam(required = false, defaultValue = "0") Integer completedQuantity,
                                       @RequestParam(required = false, defaultValue = "0") Double actualHours,
                                       @RequestParam(required = false) String remark) {
        try {
            mesProductionPlanService.completePlan(planId, employeeId, completedQuantity, actualHours, remark);
            return Result.OK("生产计划已完成！");
        } catch (Exception e) {
            log.error("生产计划完成失败", e);
            return Result.error("完成失败：" + e.getMessage());
        }
    }

    /**
     * 审核生产计划
     *
     * @param planId
     * @param approved
     * @param remark
     * @return
     */
    @AutoLog(value = "生产计划-审核")
    @ApiOperation(value = "生产计划-审核", notes = "生产计划-审核")
    @PostMapping(value = "/approve")
    public Result<String> approvePlan(@RequestParam String planId,
                                      @RequestParam Boolean approved,
                                      @RequestParam(required = false) String remark) {
        try {
            mesProductionPlanService.approvePlan(planId, approved, remark);
            return Result.OK("审核完成！");
        } catch (Exception e) {
            log.error("审核失败", e);
            return Result.error("审核失败：" + e.getMessage());
        }
    }

    /**
     * 下发生产计划
     *
     * @param planId
     * @return
     */
    @AutoLog(value = "生产计划-下发")
    @ApiOperation(value = "生产计划-下发", notes = "生产计划-下发")
    @PostMapping(value = "/issue")
    public Result<String> issuePlan(@RequestParam String planId) {
        try {
            mesProductionPlanService.issuePlan(planId);
            return Result.OK("生产计划下发成功！");
        } catch (Exception e) {
            log.error("生产计划下发失败", e);
            return Result.error("下发失败：" + e.getMessage());
        }
    }

    /**
     * 获取生产计划详情（包含任务信息）
     *
     * @param planId
     * @return
     */
    @AutoLog(value = "生产计划-获取详情")
    @ApiOperation(value = "生产计划-获取详情", notes = "生产计划-获取详情")
    @GetMapping(value = "/detail/{planId}")
    public Result<MesProductionPlanVO> getPlanDetail(@PathVariable String planId) {
        MesProductionPlanVO planVO = mesProductionPlanService.getPlanDetail(planId);
        if (planVO == null) {
            return Result.error("未找到对应的生产计划");
        }
        if (planVO.getOrderId() != null && !planVO.getOrderId().isEmpty() &&
                (planVO.getOrderNo() == null || planVO.getOrderNo().isEmpty())) {
            // 通过orderId查询orderNo
            try {
                ProductSalesOrder order = productSalesOrderService.getById(planVO.getOrderId());
                if (order != null && order.getOrderNo() != null) {
                    planVO.setOrderNo(order.getOrderNo());
                }
            } catch (Exception e) {
                log.warn("获取订单编号失败，orderId: {}", planVO.getOrderId(), e);
            }
        }
        return Result.OK(planVO);
    }

    /**
     * 获取可以生成成品入库单的订单
     *
     * @return
     */
    @AutoLog(value = "生产计划-获取可入库订单")
    @ApiOperation(value = "生产计划-获取可入库订单", notes = "获取包装入库工种已完成的订单")
    @GetMapping(value = "/finished-orders")
    public Result<List<ProductSalesOrder>> getFinishedOrdersForInbound() {
        try {
            List<ProductSalesOrder> orders = mesProductionPlanService.getFinishedOrdersForInbound();
            return Result.OK(orders);
        } catch (Exception e) {
            log.error("获取可入库订单失败", e);
            return Result.error("获取失败：" + e.getMessage());
        }
    }

    /**
     * 创建合并计划（多订单明细）
     * 支持按产品明细生成具体任务的新逻辑
     */
    @AutoLog(value = "创建合并计划")
    @ApiOperation(value="创建合并计划", notes="从多个订单明细创建合并生产计划，每个产品明细与每个工种组合生成独立任务")
    @PostMapping(value = "/createMergedPlan")
    public Result<String> createMergedPlan(@RequestBody MesMergedPlanCreateVO createVO) {
        try {
            // 参数验证
            if (createVO == null) {
                return Result.error("请求参数不能为空");
            }
            if (createVO.getOrderDetailIds() == null || createVO.getOrderDetailIds().isEmpty()) {
                return Result.error("请选择订单明细");
            }
            if (createVO.getWorkTypes() == null || createVO.getWorkTypes().isEmpty()) {
                return Result.error("请配置工种信息");
            }
            if (createVO.getPlanName() == null || createVO.getPlanName().trim().isEmpty()) {
                return Result.error("请输入计划名称");
            }
            
            log.info("开始创建合并计划，订单明细数量: {}, 工种数量: {}", 
                    createVO.getOrderDetailIds().size(), 
                    createVO.getWorkTypes().size());
            
            String planId = mesProductionPlanService.createMergedPlan(createVO);
            
            // 计算预期生成的任务数量
            int expectedTaskCount = createVO.getOrderDetailIds().size() * createVO.getWorkTypes().size();
            
            log.info("创建合并计划成功，计划ID: {}, 预期生成任务数量: {}", planId, expectedTaskCount);
            
            return Result.OK(planId, String.format("创建合并计划成功，已生成 %d 个具体任务", expectedTaskCount));
        } catch (Exception e) {
            log.error("创建合并计划失败，订单明细: {}, 错误信息: {}", 
                    createVO != null ? createVO.getOrderDetailIds() : "null", e.getMessage(), e);
            return Result.error("创建合并计划失败: " + e.getMessage());
        }
    }

    /**
     * 获取生产计划详细信息（包含订单明细和任务参与者）
     */
    @AutoLog(value = "获取生产计划详细信息")
    @ApiOperation(value="获取生产计划详细信息", notes="获取包含订单明细和任务参与者的详细信息")
    @GetMapping(value = "/getDetailedPlan/{planId}")
    public Result<MesProductionPlanDetailVO> getDetailedPlan(@PathVariable("planId") String planId) {
        try {
            MesProductionPlanDetailVO detailVO = mesProductionPlanService.getDetailedPlan(planId);
            if (detailVO == null) {
                return Result.error("未找到对应的生产计划");
            }
            return Result.OK(detailVO);
        } catch (Exception e) {
            log.error("获取生产计划详细信息失败", e);
            return Result.error("获取生产计划详细信息失败: " + e.getMessage());
        }
    }

    /**
     * 检查订单明细是否可以添加到计划中
     */
    @AutoLog(value = "检查订单明细是否可以添加到计划中")
    @ApiOperation(value="检查订单明细是否可以添加到计划中", notes="检查订单明细是否可以添加到计划中")
    @PostMapping(value = "/canAddOrderDetails")
    public Result<Boolean> canAddOrderDetailsToPlan(@RequestParam("planId") String planId,
                                                   @RequestParam("orderDetailIds") List<String> orderDetailIds) {
        try {
            boolean canAdd = mesProductionPlanService.canAddOrderDetailsToPlan(planId, orderDetailIds);
            return Result.OK(canAdd);
        } catch (Exception e) {
            log.error("检查订单明细失败", e);
            return Result.error("检查订单明细失败: " + e.getMessage());
        }
    }

    /**
     * 添加订单明细到计划中
     */
    @AutoLog(value = "添加订单明细到计划中")
    @ApiOperation(value="添加订单明细到计划中", notes="添加订单明细到计划中")
    @PostMapping(value = "/addOrderDetails")
    public Result<Void> addOrderDetailsToPlan(@RequestParam("planId") String planId,
                                             @RequestParam("orderDetailIds") List<String> orderDetailIds) {
        try {
            boolean result = mesProductionPlanService.addOrderDetailsToPlan(planId, orderDetailIds);
            if (result) {
                return Result.OK("添加订单明细成功");
            } else {
                return Result.error("添加订单明细失败");
            }
        } catch (Exception e) {
            log.error("添加订单明细失败", e);
            return Result.error("添加订单明细失败: " + e.getMessage());
        }
    }

    /**
     * 从计划中移除订单明细
     */
    @AutoLog(value = "从计划中移除订单明细")
    @ApiOperation(value="从计划中移除订单明细", notes="从计划中移除订单明细")
    @PostMapping(value = "/removeOrderDetails")
    public Result<Void> removeOrderDetailsFromPlan(@RequestParam("planId") String planId,
                                                  @RequestParam("orderDetailIds") List<String> orderDetailIds) {
        try {
            boolean result = mesProductionPlanService.removeOrderDetailsFromPlan(planId, orderDetailIds);
            if (result) {
                return Result.OK("移除订单明细成功");
            } else {
                return Result.error("移除订单明细失败");
            }
        } catch (Exception e) {
            log.error("移除订单明细失败", e);
            return Result.error("移除订单明细失败: " + e.getMessage());
        }
    }

    /**
     * 根据任务领取人获取参与的计划列表
     */
    @AutoLog(value = "根据任务领取人获取参与的计划列表")
    @ApiOperation(value = "根据任务领取人获取参与的计划列表", notes = "根据员工在任务中的参与情况获取相关计划")
    @GetMapping(value = "/byTaskOwnership")
    public Result<IPage<MesProductionPlan>> getPlansByTaskOwnership(
            @RequestParam String employeeId,
            @RequestParam Integer planStatus,
            @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        try {
            IPage<MesProductionPlan> pageList = mesProductionPlanService.getPlansByTaskOwnership(
                employeeId, planStatus, pageNo, pageSize);

            // 填充orderNo字段和任务统计
            if (pageList.getRecords() != null && !pageList.getRecords().isEmpty()) {
                for (MesProductionPlan plan : pageList.getRecords()) {
                    // 填充订单编号
                    if (plan.getOrderId() != null && !plan.getOrderId().isEmpty() &&
                            (plan.getOrderNo() == null || plan.getOrderNo().isEmpty())) {
                        try {
                            ProductSalesOrder order = productSalesOrderService.getById(plan.getOrderId());
                            if (order != null && order.getOrderNo() != null) {
                                plan.setOrderNo(order.getOrderNo());
                            }
                        } catch (Exception e) {
                            log.warn("获取订单编号失败，orderId: {}", plan.getOrderId(), e);
                        }
                    }

                    // 统计任务数据
                    try {
                        List<MesProductionPlanTask> tasks = mesProductionPlanTaskService.getTasksByPlanId(plan.getId());
                        int totalTasks = tasks.size();
                        int completedTasks = 0;
                        int pendingTasks = 0;

                        for (MesProductionPlanTask task : tasks) {
                            if (task.getStatus() != null) {
                                if (task.getStatus() == 3) { // 已完成
                                    completedTasks++;
                                } else if (task.getStatus() == 0) { // 待领取
                                    pendingTasks++;
                                }
                                // 状态1-已领取, 2-进行中, 4-暂停 不计入待处理，这些是正在处理的任务
                            }
                        }

                        // 设置任务统计数据到计划对象
                        plan.setTotalTasks(totalTasks);
                        plan.setCompletedTasks(completedTasks);
                        plan.setPendingTasks(pendingTasks);

                    } catch (Exception e) {
                        log.warn("统计计划任务数据失败，planId: {}", plan.getId(), e);
                        // 设置默认值
                        plan.setTotalTasks(0);
                        plan.setCompletedTasks(0);
                        plan.setPendingTasks(0);
                    }
                }
            }
            return Result.OK(pageList);
        } catch (Exception e) {
            log.error("获取参与计划列表失败", e);
            return Result.error("获取参与计划列表失败：" + e.getMessage());
        }
    }

    /**
     * 导出excel
     *
     * @param request
     * @param mesProductionPlan
     */
    @RequestMapping(value = "/exportXls")
    public void exportXls(HttpServletRequest request, HttpServletResponse response, MesProductionPlan mesProductionPlan) {
        super.exportXls(request, mesProductionPlan, MesProductionPlan.class, "生产计划");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, MesProductionPlan.class);
    }
}
